<template>
	<view class="page">
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="nav-content">
				<view class="nav-left" @click="blackWork">
					<image class="back-icon" src="@/static/images/back.png" mode="widthFix" />
				</view>
				<view class="nav-title3">{{ title }}</view>
				<view class="nav-right"></view>
			</view>
		</view>
		<uni-card class="content">
			<uni-forms :modelValue="formData">
				<uni-forms-item label="制单人" name="makeOrderUser">
					<uni-easyinput type="text" disabled v-model="formData.makeOrderUser" placeholder="请输入制单人" />
				</uni-forms-item>
				<uni-forms-item label="销售日期" name="saleDate">
					<uni-datetime-picker @close="onDateClose" @show="onDateOpen" v-model="formData.saleDate" type="date"
						placeholder="选择日期范围" disabled class="search-input" />
				</uni-forms-item>
				<uni-forms-item label="购货单位" name="fCustName">
					<uni-easyinput type="text" v-model="formData.fCustName" @focus="changePage" placeholder="请输入购货单位" />
				</uni-forms-item>
				<uni-forms-item label="客户电话" name="fTel">
					<uni-easyinput type="text" v-model="formData.fTel" placeholder="请输入购货单位" />
				</uni-forms-item>
				<uni-forms-item label="交货地点" name="fAddress">
					<uni-easyinput type="text" v-model="formData.fAddress" placeholder="请输入交货地点" />
				</uni-forms-item>
        <!-- 添加总金额显示 -->
        <uni-forms-item label="总金额" name="totalAmount">
          <uni-easyinput type="text" disabled v-model="formData.totalAmount" placeholder="总金额" />
        </uni-forms-item>
				<uni-forms-item label="备注" name="fNote">
					<uni-easyinput type="text" @change="saveNote" clearable="false" v-model="formData.fNote"
						placeholder="请输入备注" />
				</uni-forms-item>
			</uni-forms>
		</uni-card>
		<uni-card>
			<view class="container">
				<!-- 添加商品按钮 -->
				<view class="header">
					<text>商品清单：</text>
					<view style="background-color: aquamarine;border-radius:8px;" @click="addGoods">添加商品</view>
				</view>
				<hr>
				<!-- 商品列表 -->
				<view class="goods-list">
					<view class="goods-card" v-for="(item,index) in goodsList" :key="index">
						<!-- 商品标题 + 删除 -->
						<view class="goods-header">
							<text class="goods-title">{{ item.name }}</text>
							<text class="delete" @click="removeGoods(index)">🗑</text>
						</view>

						<!-- 商品信息 -->
            <view class="goods-info">
              <view class="row">
                <text>单位：{{ item.unit }}</text>
<!--                <text>出厂价：{{ item.factoryPrice }}</text>-->
                <text>库存：{{ item.stock }}</text>
              </view>
<!--              <view class="row">
                <text>库存：{{ item.stock }}</text>
              </view>-->
              <view class="row">
                <text class="spec-text">规格：{{ item.spec }}</text>
              </view>
              <view class="row">
                <text>数量：</text>
                <uni-easyinput v-model="item.num" type="digit" placeholder="请输入数量"
                               @input="updateTotal(index)" class="num-input" />
                <text>价格：</text>
                <uni-easyinput type="digit" v-model="item.price" placeholder="请输入价格"
                               @input="updateTotal(index)" class="price-input" />
              </view>
              <view class="row">
                <text>金额：{{ item.total }}</text>
              </view>
            </view>
					</view>
				</view>
			</view>
		</uni-card>

		<!-- 确认按钮 -->
		<view class="confirm-bar" :style=" { zIndex: footerZ }">
			<button :disabled="isSubmitting" class="btn-confirm" @click="commitOrder">提交订单</button>
		</view>
	</view>
</template>

<script>
	import {
		commitShop,
		salesUpdate
	} from '@/api/saleOrder.js'
	export default {


		data() {
			return {
				statusBarHeight: 0,
				title: '移动下单',
				mode: "add",
				footerZ: 100,
				isSubmitting: false,
				formData: {
					fNote: "",
					fCustName: "",
					fTel: "",
					fAddress: "",
					saleDate: "",
					makeOrderUser: this.$store.state.user.name,
          totalAmount: 0  // 添加总金额字段
				},
				goodsList: []
			}
		},

    // 添加计算属性来自动计算总金额
    computed: {
      calculatedTotalAmount() {
        return this.goodsList.reduce((total, item) => {
          return total + parseFloat(item.total || 0);
        }, 0).toFixed(2);
      }
    },

    watch: {
      // 监听计算后的总金额变化，同步到 formData
      calculatedTotalAmount(newVal) {
        this.formData.totalAmount = newVal;
      }
    },

		onLoad(options) {
			// 获取状态栏高度，适配刘海屏/不同手机
			const sys = uni.getSystemInfoSync()
			this.statusBarHeight = sys.statusBarHeight || 20
			if (options.mode) {
				uni.setStorageSync("mode", options.mode)
				this.mode = options.mode || 'add';
			} else {
				this.mode = uni.getStorageSync("mode");
			}

			if (this.mode === 'edit') {
				// debugger
				const editOrderData = uni.getStorageSync("editOrderData");
				if (editOrderData) {
					// 填充表单数据
					this.formData.fCustName = editOrderData.fCustId_FName;
					this.formData.saleDate = editOrderData.fDate;
					this.formData.fTel = editOrderData.fReceiveContact;
					this.formData.fAddress = editOrderData.fDetailLocAddress;
					this.formData.fNote = editOrderData.fNote;
					this.formData.fBillNo = editOrderData.fBillNo;
					this.formData.fId = editOrderData.fId;
					this.formData.fCustId_FNumber = editOrderData.fCustId_FNumber
					let entity = [];
					if (editOrderData.fEntry.length > 0) {
						entity = editOrderData.fEntry.map(item => {
							return {
								// 左边是你前端 goodsList 需要的字段
								// 右边是后端返回的字段
								name: item.fMaterialId_FName, // 物料名称
								fEntryID: item.fEntryID, //
								factoryPrice: Number(item.ftaxPrice).toFixed(1),
								unit: item.funitID_FName, // 单位
								price: Number(item.ftaxPrice).toFixed(1), // 单价，保留1位小数
								num: Number(item.fQty).toFixed(1), // 数量，保留1位小数
								total: (Number(item.ftaxPrice) * Number(item.fQty)).toFixed(1), // 金额，保留1位小数
								stock: Number(item.fstockQty || 0).toFixed(1), // 库存，保留1位小数 // 库存，后端可能没返回就默认 0
								spec: item.fmaterialId_FSpecification || '' // 规格
							}
						})
					}


					// TODO: 商品明细（需要你接口返回的格式）
					this.goodsList = uni.getStorageSync("goodsList") || entity || [];
					this.formatDate()
					const source = options.source

					if (source === 'customer') {
						const data = JSON.parse(decodeURIComponent(options.data))
						console.log('来自客户信息选择：', data)
						this.handleCustomerData(data)
						uni.setStorageSync("saveNote", this.formData.fNote);
					} else if (source === 'goods') {
						const data = JSON.parse(decodeURIComponent(options.data))
						uni.setStorageSync("goodsList", this.goodsList)
						console.log('来自商品选择：', data)
						this.handleShopData(data)
						uni.setStorageSync("goodsList", this.goodsList)
					}
				}
				if ("" != uni.getStorageSync("saveNote")) {
					this.formData.fNote = uni.getStorageSync("saveNote")
				}

			} else {
				this.formatDate()
				const cachedForm = uni.getStorageSync("formData");
				if (cachedForm) {
					this.formData = {
						...this.formData,
						...cachedForm
					};
				}

				this.formData.fNote = uni.getStorageSync("saveNote");
				// 每次进入页面时，优先从缓存恢复 goodsList
				const cachedGoods = uni.getStorageSync("goodsList") || [];

        // 不管什么情况都先恢复 goodsList
        this.goodsList = cachedGoods;

				if (options.data && options.source) {
					const source = options.source

					if (source === 'customer') {
						const data = JSON.parse(decodeURIComponent(options.data))
						console.log('来自客户信息选择：', data)
						this.handleCustomerData(data)
					} else if (source === 'goods') {

						this.goodsList = cachedGoods;
						const data = JSON.parse(decodeURIComponent(options.data))
						console.log('来自商品选择：', data)
						this.handleShopData(data)
					}
				}
			}


			options = null;

		},
		methods: {
			blackWork() {
				uni.reLaunch({
					url: '/pages/work/index'
				})
			},
			onDateOpen() {
				// 打开日期时把底部放到更低层或隐藏
				this.footerZ = 0
			},
			onDateClose() {
				// 关闭时恢复
				this.footerZ = 100
			},
			updateTotal(index) {
				const item = this.goodsList[index]
				const num = Number(item.num) || 0
				const price = Number(item.price) || 0
				item.total = (num * price).toFixed(2) // 保留两位小数
				// 触发视图更新
				this.$set(this.goodsList, index, item)
				uni.setStorageSync("goodsList", this.goodsList)
			},
			changePage() {
				uni.navigateTo({
					url: `/pages/customer/index`
				}).catch(e => {
					uni.showToast(e)
				})
			},
			handleShopData(data) {
				// data 是数组
				let goodsListData = uni.getStorageSync("goodsList") || []

				data.forEach(item => {
					let obj = {
						name: item.fMaterialName,
						unit: item.fBaseUnitName,
						factoryPrice: item.fFactoryPrice,
						stock: item.fBaseqty,
						spec: item.fSpecification,
						num: 0,
						price: 0,
						total: 0,
						fMaterialNumber: item.fMaterialNumber
					}
					// 避免重复添加，可以先判断一下 fMaterialNumber
					/* if (!goodsListData.some(g => g.fMaterialNumber === obj.fMaterialNumber)) {
						goodsListData.push(obj)
					} */
					
					goodsListData.push(obj)
				})

				// 更新 data 和缓存
				this.goodsList = goodsListData
				uni.setStorageSync("goodsList", goodsListData)
			},
			handleCustomerData(data) {
				this.formData.fAddress = data.fAddress;
				this.formData.fCustName = data.fCustName;
				this.formData.fCustId = data.fCustId;
				this.formData.fCustNumber = data.fCustNumber;
				this.formData.fTel = data.fTel;
				this.formData.makeOrderUser = this.$store.state.user.name;

				uni.setStorageSync("formData", this.formData);
			},
			// 格式化为 'YYYY-MM-DD' 字符串
			formatDate() {
				let date = new Date()
				const y = date.getFullYear()
				const m = String(date.getMonth() + 1).padStart(2, '0')
				const d = String(date.getDate()).padStart(2, '0')
				this.formData.saleDate = `${y}-${m}-${d}`
			},
			addGoods() {
				uni.navigateTo({
					url: "/pages/shop/index"
				}).catch(e => {
					uni.showToast(e)
				})
			},
			removeGoods(index) {
				this.goodsList.splice(index, 1);
				uni.setStorageSync("goodsList", this.goodsList); // 删除后也更新缓存
			},
			saveNote() {
				uni.setStorageSync("saveNote", this.formData.fNote);
			},
			commitOrder() {
				if (this.isSubmitting) {
					uni.showToast({
						title: '提交中请耐心等待！！', // 显示的文字
						icon: 'warn', // success / loading / none
						duration: 2000 // 持续时间，单位 ms
					});
					return;
				};

        // ✅ 验证商品列表中的数量和价格
        const invalidGoods = this.goodsList.filter(item =>
            !item.num || parseFloat(item.num) <= 0 ||
            !item.price || parseFloat(item.price) <= 0
        );

        if (invalidGoods.length > 0) {
          uni.showToast({
            title: '商品数量和价格必须大于0',
            icon: 'none',
            duration: 2000
          });
          return;
        }

				// ✅ 防重复点击
				this.isSubmitting = true;
				// debugger
				uni.showLoading({
					title: "数据提交中，请稍后"
				});
				let that = this
				const data = {
					form: this.formData,
					goods: this.goodsList,
				};

				try {
					let res;
					if (that.mode === 'edit') {

						res = that.updateSaleOrder(data);
						uni.hideLoading()
						// 修改接口
					} else {
						res = that.submitAddForm(); // 新增接口
						uni.hideLoading()
					}
				} catch (e) {

					uni.showToast({
						title: "提交异常",
						icon: "none"
					});
					this.isSubmitting = false;
				} finally {
					uni.hideLoading();
					// this.isSubmitting = false;
					uni.removeStorageSync("mode")
				}
			},
			updateSaleOrder(data) {
				// debugger
				uni.showLoading("数据提交中，请稍后")
				let obj = {
					fSalerId_FName: this.$store.state.user.name,
					fCustId_FNumber: this.formData.fCustId_FNumber,
					fDetailLocAddress: this.formData.fAddress,
					fReceiveContact: this.formData.fTel,
					fNote: this.formData.fNote,
					fId: this.formData.fId
				}

				const fEntry = this.goodsList.map(item => {
					return {
						fMaterialId_FNumber: item.fMaterialNumber,
						fSalerId_FName: this.$store.state.user.name,
						fAmount: item.price,
						fQty: item.num,
						fEntryID: item.fEntryID
					}
				})
				obj.fEntry = fEntry
				salesUpdate(obj).then(res => {
					if (res.data.Result.ResponseStatus.IsSuccess) {
						uni.showToast({
							title: "修改成功",
							icon: 'success'
						})
						this.goodsList = []
						uni.removeStorageSync("goodsList")

						// 也可以重置 formData
						this.formData = {
							fCustName: "",
							fTel: "",
							fAddress: "",
							saleDate: this.formData.saleDate, // 保留当天日期
							makeOrderUser: this.$store.state.user.name,
							fNote: ""
						}
						uni.navigateTo({
							url: "/pages/saleOrder/index"
						})
						uni.removeStorageSync("saveNote");
						uni.removeStorageSync("formData"); // ✅ 清空客户缓存
						uni.removeStorageSync("editOrderData");

					} else {

						uni.showModal({
							title: res.data.Result.ResponseStatus.Errors[0].Message,
							icon: 'error'
						})
					}
				}).catch(e => {
					uni.hideLoading()
				})
			},
			submitAddForm() {
				// debugger
				let that = this;
				uni.showLoading("数据提交中，请稍后")
				let obj = {

					fSalerId_FName: this.$store.state.user.name,
					fCustId_FNumber: this.formData.fCustNumber,
					fDetailLocAddress: this.formData.fAddress,
					fReceiveContact: this.formData.fTel,
					fNote: this.formData.fNote
				}
				const fEntry = this.goodsList.map(item => {
					return {
						fMaterialId_FNumber: item.fMaterialNumber,
						fEntryID: item.fEntryID,
						fSalerId_FName: this.$store.state.user.name,
						fFactoryPrice: item.factoryPrice,
						fAmount: item.price,
						fQty: item.num,
					}
				})
				obj.fEntry = fEntry
				commitShop(obj).then(res => {
					console.log(res.data.Result.ResponseStatus.IsSuccess + "1111111111")
					if (res.code == 200) {
						console.log(res.data.Result.ResponseStatus.IsSuccess + "1111111111")
						if (res.data.Result.ResponseStatus.IsSuccess) {
							uni.showToast({
								title: "推送成功",
								icon: 'success'
							})
							this.goodsList = []
							uni.removeStorageSync("goodsList")

							// 也可以重置 formData
							this.formData = {
								fCustName: "",
								fTel: "",
								fAddress: "",
								saleDate: this.formData.saleDate, // 保留当天日期
								makeOrderUser: this.$store.state.user.name,
								fNote: ""
							}
							uni.removeStorageSync("saveNote");
							uni.removeStorageSync("formData"); // ✅ 清空客户缓存

							uni.redirectTo({
								url: `/pages/saleOrder/index`
							})
						} else {

							uni.showModal({
								title: res.data.Result.ResponseStatus.Errors[0].Message,
								icon: 'error'
							})
						}



					}



				}).catch(error => {
					that.hideLoading();
				})

			}
		}
	}
</script>

<style scoped>
	.page {
		padding: 10rpx;
		padding-bottom: 120rpx;
		/* 给底部按钮留出空间 */
	}

	.custom-navbar {
		width: 100%;
		background-color: #ffffff;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
		z-index: 1000;
	}

	.nav-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;
		padding: 0 10px;
	}

	/* 左侧返回按钮区域 */
	.nav-left {
		width: 60rpx;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.back-icon {
		width: 22px;
		height: 22px;
	}

	/* 中间标题 */
	.nav-title3 {
		flex: 1;

		text-align: center;
		font-size: 26rpx;
		font-weight: 500;
		color: #000;
	}

	/* 右侧预留空间（对称用） */
	.nav-right {
		width: 60rpx;
	}

	/* 左侧返回按钮区域 */
	.nav-left {
		width: 60rpx;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.back-icon {
		width: 22px;
		height: 22px;
	}

	/* 中间标题 */
	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 17px;
		font-weight: 500;
		color: #000;
	}

	/* 右侧预留空间（对称用） */
	.nav-right {
		width: 60rpx;
	}

	/* “返回”文字 */
	.back-text {
		font-size: 16px;
		color: #333;
		margin-left: 2px;
	}

	/* 标题居中 */
	.title {
		font-size: 18px;
		font-weight: bold;
		color: #000;
	}

	/* 内容 */
	.content {
		padding-top: 60px;
	}

	.confirm-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		padding: 20rpx;
		/* 去掉 margin，否则会被顶起来 */
		margin: 0;
		height: 100rpx;
		/* 固定高度 */
		border-radius: 16rpx 16rpx 0 0;
		/* 只保留上圆角，看起来更自然 */
		box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);

		/* 确保浮在最上层 */
	}

	.btn-confirm {
		width: 100%;
		height: 80rpx;
		background: #007AFF;
		color: #fff;
		border-radius: 8px;
		font-size: 16px;
		font-weight: bold;
	}

	.container {
		padding: 10rpx;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.goods-card {
		background: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.goods-header {
		display: flex;
		justify-content: space-between;
		font-weight: bold;
		margin-bottom: 12rpx;
	}

	.delete {
		color: red;
		font-size: 28rpx;
	}

	.goods-info .row {
		display: flex;
		justify-content: space-between;
		margin: 6rpx 0;
		font-size: 28rpx;
	}

  /* 在现有样式基础上添加以下优化 */
  .goods-info .row {
    display: flex;
    justify-content: space-between;
    margin: 6rpx 0;
    font-size: 28rpx;
    overflow: hidden; /* 防止内容溢出 */
  }

  /* 为规格字段添加文本截断 */
  .spec-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 600rpx; /* 限制最大宽度 */
  }

  /* 为价格和数量输入框添加固定宽度 */
  .price-input,
  .num-input {
    width: 150rpx;
    margin-right: 20rpx;
  }

  /* 添加响应式处理 */
  @media (max-width: 375px) {
    .spec-text {
      max-width: 550rpx;
    }

    .price-input,
    .num-input {
      width: 120rpx;
    }
  }
</style>